package pers.jphoebe.quartz.config.db;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import pers.jphoebe.quartz.utils.Logger;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * Created by 蒋时华 on 2017/11/1.
 */
@Configuration
@MapperScan(basePackages = "pers.jphoebe.quartz.dao.h2", sqlSessionTemplateRef  = "h2SessionTemplate")
public class H2DatasourceConfiguration {

    private Logger logger = Logger.getLogger(this.getClass());

    @Bean(name = "h2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.h2")
    public DataSource secondaryDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "h2SessionFactory")
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("h2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/h2/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "h2TransactionManager")
    public DataSourceTransactionManager secondaryTransactionManager(@Qualifier("h2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "h2SessionTemplate")
    public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("h2SessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
